<template>
  <div class="maincontain">
    <div class="createuser">
      <div class="btn">
        <a-button
          @click="goUserEditor(FormType.Create)"
          type="primary"
          style="margin-right: 10px"
          >新增用户</a-button
        >
        <a-button
          @click="
            () => {
              BatchModalState(true);
            }
          "
          type="primary"
          style="margin-right: 10px"
          >批量导入</a-button
        >
      </div>
      <div class="inputfilter">
        <div class="top">
          <a-input
            class="search-item"
            addon-before="用户名"
            v-model:value="fitlerState.username"
            placeholder="输入用户名查询"
            @change="onSearch"
          />
          <a-input
            class="search-item"
            addon-before="账号"
            v-model:value="fitlerState.account"
            placeholder="输入账号查询"
            @change="onSearch"
          />
          <a-input
            class="search-item"
            addon-before="email"
            v-model:value="fitlerState.email"
            placeholder="输入email查询"
            @change="onSearch"
          />
          <span class="search-item">
            选择角色：<a-select
              class="search-item"
              v-model:value="fitlerState.role"
              @change="onSearch"
              :options="roleOptions"
            />
          </span>
        </div>
        <div class="bottom">
          <a-input
            class="search-item"
            addon-before="职级"
            v-model:value="fitlerState.title"
            placeholder="输入职级查询"
            @change="onSearch"
          />
          <a-input
            class="search-item"
            addon-before="专业"
            v-model:value="fitlerState.profession"
            placeholder="输入专业查询"
            @change="onSearch"
          />
          <a-input
            class="search-item"
            addon-before="班级"
            v-model:value="fitlerState.className"
            placeholder="输入班级查询"
            @change="onSearch"
          />
          <span class="search-item">
            选择性别：<a-select
              class="search-item"
              v-model:value="fitlerState.gender"
              @change="onSearch"
              :options="genderOptions"
            />
          </span>
        </div>
      </div>
    </div>
    <div class="filter-bar"></div>
    <div class="userlist">
      <a-table
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        :dataSource="dataSource"
        :columns="columsConfig"
      >
        <template #bodyCell="{ column, record }">
          <template v-if="column.key === 'operator'">
            <a-space wrap>
              <a-button
                size="small"
                type="primary"
                @click="
                  () => {
                    goUserEditor(FormType.Update, record.order);
                  }
                "
                >编辑</a-button
              >
              <a-button
                danger
                size="small"
                @click="
                  () => {
                    deleteUserModal(record.username, record.order);
                  }
                "
                >删除</a-button
              >
              <a-button
                size="small"
                @click="
                  () => {
                    resetUserPassword(record.username, record.order);
                  }
                "
                >重置密码</a-button
              >
            </a-space>
          </template>
          <template v-if="column.key === 'gender'">
            <span>{{ record.gender === 0 ? "男" : "女" }}</span>
          </template>
          <template v-if="column.key === 'role'">
            <span>{{ record.role }}</span>
          </template>
          <template v-if="column.key === 'avatarUrl'">
            <a-image :width="50" :src="record.avatarUrl" />
          </template>
        </template>
      </a-table>
    </div>
  </div>
  <a-modal v-model:open="batchModalShow" title="批量导入文件">
    <div class="clearfix">
      <a-upload
        :file-list="fileListExcel"
        :before-upload="beforeUpload"
        @remove="handleRemove"
        :disabled="fileListExcel?.length === 1"
      >
        <a-button :disabled="fileListExcel?.length === 1">
          <upload-outlined></upload-outlined>
          Select File
        </a-button>
      </a-upload>
      <a-button
        type="primary"
        :disabled="fileListExcel!.length === 0"
        :loading="uploading"
        style="margin-top: 16px"
        @click="handleUpload"
      >
        {{ uploading ? "Uploading" : "Start Upload" }}
      </a-button>
    </div>
  </a-modal>
</template>

<script lang="ts" setup>
import { computed, createVNode, onMounted, ref } from "vue";
import { columsConfig } from "./config";
import {
  deleteUserInfo,
  resetPassword,
  userBatchImport,
  userBatchQuery,
} from "@/api/methods/userReq";
import { type IUser } from "@/api/RequestIDL/userType";
import dayjs from "dayjs";
import { debounce, omit } from "lodash";
import { useRouter } from "vue-router";
import { FormType } from "@/EnvEnum/form";
import { Message } from "@/utils/message";
import { Modal } from "ant-design-vue";
import { ExclamationCircleOutlined } from "@ant-design/icons-vue";
import { UploadProps } from "antd/es/upload/Upload";

const router = useRouter();
const dataSource = ref();
const pageConfig = ref({
  pageSize: 10,
  page: 1,
  total: 0,
});
export interface IPagenation {
  current: number;
  pageSize: number;
  total: number;
}
const pagination = computed(() => ({
  total: pageConfig.value.total,
  current: pageConfig.value.page,
  pageSize: pageConfig.value.pageSize,
}));
const fitlerState = ref<Partial<IUser>>({
  account: "",
  className: "",
  gender: "",
  profession: "",
  role: "",
  title: "",
  username: "",
  email: "",
});
const roleOptions = [
  { label: "管理员", value: "0" },
  { label: "实验员", value: "1" },
  { label: "教师", value: "2" },
  { label: "学生", value: "3" },
];
const genderOptions = [
  { label: "男", value: "0" },
  { label: "女", value: "1" },
];
const searchConfig = computed(() => {
  return {
    ...omit(pageConfig.value, "total"),
    ...fitlerState.value,
  };
});
const loading = ref(false);
const handleTableChange = async (pagination: IPagenation) => {
  pageConfig.value.page = pagination.current;
  pageConfig.value.pageSize = pagination.pageSize;
  getUserInfoList();
};
const getUserInfoList = async () => {
  loading.value = true;
  console.log(searchConfig.value);
  const { data: res } = await userBatchQuery(searchConfig.value);
  reflectMapDataSource(res);
  loading.value = false;
};
onMounted(async () => {
  getUserInfoList();
});
const reflectMapDataSource = (res: any) => {
  pageConfig.value.total = res.total;
  const roleMap = ["管理员", "实验员", "教师", "学生"];
  dataSource.value = res.records.map((item: IUser) => {
    return {
      account: item.account,
      username: item.username,
      updateTime: dayjs(item.updateTime).format(
        import.meta.env.APP_FORMAT_TIME
      ),
      role: roleMap[item.role],
      avatarUrl: item.avatarUrl,
      gender: item.gender,
      order: item.id,
      className: item.className,
      profession: item.profession,
      title: item.title,
      createTime: dayjs(item.createTime).format(
        import.meta.env.APP_FORMAT_TIME
      ),
    };
  });
};
/**
 * 跳转新增
 */
const goUserEditor = (FormType: FormType, userId?: number) => {
  router.push({
    name: "userCreate",
    query: {
      formType: FormType,
      userId: userId || undefined,
    },
  });
};
const deleteUserModal = (username: string, userId: number) => {
  Modal.confirm({
    title: "删除提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      "div",
      { style: "color:red;" },
      `确定要删除【${username}】用户吗？`
    ),
    onOk() {
      deleteUser(userId);
    },
    onCancel() {},
  });
};
const resetUserPassword = (username: string, userId: number) => {
  Modal.confirm({
    title: "删除提示",
    icon: createVNode(ExclamationCircleOutlined),
    content: createVNode(
      "div",
      { style: "color:red;" },
      `确定要重置【${username}】用户密码吗？`
    ),
    onOk() {
      resetUserPasswordReq(userId);
      // 重新拉取列表
      setTimeout(() => {
        getUserInfoList();
      }, 500);
    },
    onCancel() {},
  });
};
const deleteUser = async (userId: number) => {
  const res = await deleteUserInfo({ id: userId });
  if (res.code === 20000) {
    Message("success", "用户删除成功");
    getUserInfoList();
  }
};
const resetUserPasswordReq = async (userId: number) => {
  const res = await resetPassword({ id: userId });
  if (res.code === 20000) {
    Message("success", "密码重置成功");
  } else {
    Message("error", "密码重置失败，联系管理员");
  }
};
const onSearch = debounce(
  () => {
    getUserInfoList();
  },
  500,
  { maxWait: 1000 }
);

// 批量导入模块
const headers = {
  authorization: "authorization-text",
};
const fileListExcel = ref<UploadProps["fileList"]>([]);
const batchModalShow = ref(false);
const BatchModalState = (val: boolean) => {
  batchModalShow.value = val;
};
const handleRemove: UploadProps["onRemove"] = (file) => {
  const index = fileListExcel.value!.indexOf(file);
  const newFileList = fileListExcel.value!.slice();
  newFileList.splice(index, 1);
  fileListExcel.value = newFileList;
};
const uploading = ref(false);
const beforeUpload: UploadProps["beforeUpload"] = (file) => {
  //@ts-ignore
  fileListExcel.value = [...(fileListExcel.value || []), file];
  return false;
};
const handleUpload = () => {
  const formData = new FormData();
  console.log(fileListExcel.value);
  fileListExcel.value!.forEach((file: UploadProps["fileList"][number]) => {
    formData.append("file", file as any, file.name);
  });
  userBatchImport(formData)
    .then((res) => {
      if (res.code) {
        BatchModalState(false);
        fileListExcel.value = [];
        uploading.value = false;
        Message("success", "批量导入成功");
      } else {
        uploading.value = false;
        fileListExcel.value = [];
        Message("danger", "批量导入失败");
      }
    })
    .catch(() => {
      uploading.value = false;
      Message("danger", "批量导入失败");
    });
};
</script>
<style scoped lang="scss">
/* @import url(); 引入css类 */
.maincontain {
  display: flex;
  flex-direction: column;
  .createuser {
    margin-bottom: 15px;
    display: flex;
    flex-direction: column;
    .inputfilter {
      display: flex;
      flex-direction: column;
      .top {
        margin-top: 10px;
      }
      .bottom {
        margin-top: 10px;
      }
      .search-item {
        width: 200px;
        margin-right: 10px;
      }
    }
  }
}
</style>
